import Vue from "vue";
import VueRouter from "vue-router";
import Layouts from "../layouts";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    redirect: "/login",
  },
  {
    path: "/login",
    meta: { title: "登录" },
    component: () => import("../views/login.vue"),
  },
  {
    path: "/register",
    meta: { title: "注册" },
    component: () => import("../views/register.vue"),
  },
  {
    path: "/home",
    component: Layouts,
    children: [
      {
        path: "",
        meta: { title: "首页", icon: "el-icon-s-home" },
        component: () => import("../views/home/index.vue"),
      },
    ],
  },
  {
    path: "/system",
    component: Layouts, // 如果系统管理有公共布局，可以保留
    meta: { title: "管理", icon: "el-icon-s-home" },
    children: [
      {
        path: "user",
        meta: { title: "用户管理", icon: "el-icon-s-home" },
        component: () => import("../views/system/user/index.vue"),
      },
      {
        path: "team",
        meta: { title: "批次管理", icon: "el-icon-s-home" },
        component: () => import("../views/system/team/index.vue"),
      },
      {
        path: "testPer",
        meta: { title: "参测人员管理", icon: "el-icon-s-home" },
        component: () => import("../views/system/testPer/index.vue"),
      },
    ],
  },
  {
    path: "/assess",
    component: Layouts, // 如果系统管理有公共布局，可以保留
    meta: { title: "评估管理", icon: "el-icon-s-home" },
    children: [
      {
        path: "topic",
        meta: { title: "题目管理", icon: "el-icon-s-home" },
        component: () => import("../views/assess/topic/index.vue"),
      },
    ],
  },
  {
    path: "/updatePw",
    component: Layouts,
    children: [
      {
        path: "",
        meta: { title: "修改用户密码", icon: "el-icon-key" },
        component: () => import("../views/updatePw/index.vue"),
      },
    ],
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});

// 前置路由拦截器
router.beforeEach((to, from, next) => {
  // 设置当前页签名称
  document.title = to.meta.title || '默认标题';

  // 检查是否需要重定向
  const token = sessionStorage.getItem("token"); // 使用 sessionStorage
  if (to.path === "/login" || token || to.path === "/register") {

    next(); // 如果是登录页面或已登录，继续
  } else {
    next("/login"); // 否则重定向到登录页面
  }
});


export default router;
